package com.order.rabbitmq.consumer;

import cn.hutool.core.util.BooleanUtil;
import com.common.exception.order.OrderException;
import com.common.rabbitmq.producer.core.OrderProducer;
import com.order.domain.pojo.Order;
import com.order.enums.OrderStatus;
import com.order.feign.PaymentFeignClient;
import com.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTaskDeadLetterConsumer {
    private final IOrderService iOrderService;
    private final OrderProducer orderProducer;
    private final PaymentFeignClient paymentFeignClient;


    /**
     * 死信队列 （延迟任务）
     * 支付服务 -》订单服务 -》更新订单状态
     */
    @RabbitListener(queues = { "order-paid-to-completed-dead-letter-queue" })
    public void orderPaidToCompletedDeadLetter(String orderNo){
        log.info("订单服务：订单延迟任务：订单 {} 从已支付变为已完成",orderNo);
        iOrderService.paidToCompleted(orderNo);
    }

    /**
     * 死信队列 - 订单定时任务校验订单状态
     * 当用户下单成功之后，每隔一段时间校验订单状态是否已经支付，超时则关闭
     *
     */
    @RabbitListener(queues = { "order-check-dead-letter-queue" })
    public void orderCheckDeadLetter(Long orderId){
        log.info("订单服务：订单定时任务校验订单状态：订单id {}",orderId);
        Order order = iOrderService.getById(orderId);
        // 1: 订单基础校验
        if (order == null){
            throw new OrderException(OrderException.ORDER_NOT_EXIST);
        }
        // 2: 校验订单是否已经超时
        LocalDateTime timeOut = order.getTimeOut();
        if (timeOut.isBefore(LocalDateTime.now())){
            log.info("订单服务：订单 {} 已超时，关闭订单",order.getOrderNo());
            iOrderService.cancel(order.getId(),true);
            return;
        }
        // 3: 订单未超时 校验订单是否已经支付
        if (!OrderStatus.isPaymentSuccess(order.getStatus())) {
            // 3.1: 此时订单未支付成功 查询支付宝是否支付成功
            Boolean tradeResult = paymentFeignClient.queryPaymentResult(order.getOrderNo()).getData();
            if (BooleanUtil.isTrue(tradeResult)){
                // 3.2: 支付成功 修改订单状态
                log.info("订单服务：订单 {} 已支付成功，修改订单状态",order.getOrderNo());
                iOrderService.paySuccess(order.getOrderNo());
            }else {
                log.warn("订单服务：订单 {} 未支付成功，等待下次校验",order.getOrderNo());
                // 3.3: 支付未成功 & 订单未超时 =》 等待下一次校验
                orderProducer.orderClickTask(order.getId());
            }
        }
    }
}
